//
//  CommonModel.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/29.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire

class CommonModel: NSObject {

    
    /// 获取表单OrderNo
    ///
    /// - Parameters:
    ///   - orderConfigId: 对应表单的orderConfigId
    ///   - completionHandler:
    class func getOrderNo(_ orderConfigId: String, completionHandler: @escaping (WWValueResponse<String?>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "MarTian.BasicHandler.AjaxCommonApp.GetAutoNumber"
        
        let params = ["Method": method, "orderConfigId":orderConfigId, "AccountId": accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let value = response.result.value as? [String: AnyObject] {
                    let status = StatusStruct(rootJson: value)
                    if status.success {
                        let orderNo = value["OrderNo"] as? String
                        completionHandler(WWValueResponse.init(value: orderNo, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据有错误"))
            }
            else {
               
                completionHandler(WWValueResponse.init(success: false, message: "网络访问错误！"))
            }
        }
    }
    
    //
    /// 校验手机号
    ///
    /// - Parameters:
    ///   - phoneNumber:
    ///   - isNewPhone: 校验的是当前号码还是新号码
    ///   - completionHandler:
    class func checkPhoneNumber(_ phoneNumber: String,isNewPhone: Bool = false, completionHandler:@escaping (WWResponse) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "MarTian.WebSitePortal.Handler.AjaxSignUp.CheckUserPhoneForApp"
        let companyType = "建筑工人"
        
        let params = ["Method":method, "companyType":companyType, "IsNewPhone":"\(isNewPhone)", "phoneNumber": phoneNumber, "AccountId": accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String, status == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        let result = dict["Result"] as? String
                        completionHandler(WWResponse.init(success: false, message: result))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "提交失败"))
            }
            else {
               
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    
    //
    /// 没有token的情况下校验手机号
    ///
    /// - Parameters:
    ///   - phoneNumber:
    ///   - needPhoneExist: 是否需要手机号存在。如果true，那么status==OK的情况回调成功，如果false,那么status=="ERROR"的情况返回成功
    ///   - completionHandler:
    class func checkPhoneNumberWithoutToken(_ phoneNumber: String, needPhoneExist:Bool = false,completionHandler:@escaping (WWResponse) -> Void) {
        
        let companyType = "建筑工人"
        
        let params = ["companyType":companyType, "phoneNumber": phoneNumber]
        
        let actionUrl = "http://app.winshe.cn/CheckUserPhoneForFindPwd"
        let actionHeader = "CheckUserPhoneForFindPwd"

        ReqWebService.reqWebService(WebServiceURL + "?op=CheckUserPhoneForFindPwd", action: actionUrl, actionHeader: actionHeader, params: params) { (response) in
            
            //返回true的情况下，表示手机号已存在。false表示手机号不存在
            if response.success {
                if let value = response.value as? [String: String] {
                    if let status = value["Status"] {
                        if needPhoneExist {
                            if status == "OK" {
                                completionHandler(WWResponse.init(success: true))
                            }
                            if status == "ERROR" {
                                completionHandler(WWResponse.init(success: false,message:"未注册，请重新输入"))
                            }
                        }
                        else {
                            if status == "OK" {
                                completionHandler(WWResponse.init(success: true, message:"该手机号码已注册，请重新输入"))
                            }
                            if status == "ERROR" {
                                completionHandler(WWResponse.init(success: true))
                            }
                        }
                        
                        return
                    }
                   
                }
                 completionHandler(WWResponse.init(success: false, message: "数据格式有误"))
            }
            else {
                
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    //修改手机号
    class func modifyPhoneNumber(_ newPhoneNumber: String,completionHandler:@escaping (WWResponse) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "MarTian.WebSitePortal.Handler.AjaxSignUp.ChangeUserPhoneForApp"
        
        let params = ["Method":method, "newPhoneNumber":newPhoneNumber, "AccountId":accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let value = response.result.value as? [String: AnyObject] {
                    let status = StatusStruct(rootJson: value)
                    if status.success {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        
                        completionHandler(WWResponse.init(success: false, message: "提交失败"))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "数据格式有错误"))
            }
            else {
                
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    /// 根据orderId获取orderConfigId
    class func getOrderConfigId(_ orderId: String,completionHandler:@escaping (WWValueResponse<String>) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        let method = "KouFine.Handler.Core.AjaxOther.GetRawClassNameByConfigId"
        
        let params = ["Method": method, "orderId": orderId, "AccountId":accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String : Any] {
                    if let configId = dict["ConfigId"] as? String {
                       completionHandler(WWValueResponse.init(value: configId, success: true))
                    }
                    else {
                        completionHandler(WWValueResponse.init(success: false, message: "获取出错"))
                    }
                    return
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
            }
            else {
                let string = String.init(data: response.data!, encoding: .utf8)
                completionHandler(WWValueResponse.init(success: false, message: string))
            }
        }
    }
}

class ImageUploadModel {
    var aId: String? //对应一个图片数据的ID
    var name: String? //图片名字
    var success: Bool? //是否成功
    var url: String? // 图片地址
    
    required init(_ jsonData: [String: Any]) {
        if let name = jsonData["Name"] {
            self.name = name as? String
        }
        if let id = jsonData["ID"] {
            self.aId = id as? String
        }
        if let success = jsonData["success"] as? Bool {
            if success == true {
                self.success = true
            }
            else {
                self.success = false
            }
        }
        if let url = jsonData["url"]  {
            self.url = url as? String
        }
    }
    
    /*上传图片。
    isCertification表示是否是认证时上传正反面身份证照片。默认不是，因为这是上传图片的默认接口，isCertification=true只是一种特殊情况
 */
    class func commitImage(_ images: [UIImage],isCertification:Bool = false ,completionHandler:@escaping (WWValueResponse<[ImageUploadModel]>) -> Void) {
        let url = URL_Header + "KouFine.Web.Core.AjaxUpload.ImageUploadAndCreateApp.kf"
        guard let token = WWUser.sharedInstance.token else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let params = ["AccountId":accountId, "token": token]
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            if isCertification == true {
                for (index, image) in images.enumerated() {
                    multipartFormData.append(compressImage(image), withName: "Photo", fileName: index == 0 ? "positive.jpg":"reverse.jpg", mimeType: "image/jpeg")
                }
            }
            else {
                
                //拼接图片数据
                for image in images {
                   multipartFormData.append(compressImage(image), withName: "Photo", fileName: "img.jpg", mimeType: "image/jpeg")
                }
                
            }
            //拼接参数
            for (key, value) in params {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
        }, to: url, method:.post) { (encodingResult) in
            switch encodingResult {
            case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
                upload.responseJSON(completionHandler: { (response) in
                    if let myjson = response.result.value as? [String: Any] {
                        if let resultInt = myjson["success"] as? Bool {
                            if resultInt == true {
//                                print("图片上传成功")
                                if let items = myjson["Items"] as? [[String: Any]] {
                                    var responseArr = [ImageUploadModel]()
                                    for item in items {
                                        let model = ImageUploadModel.init(item)
                                        responseArr.append(model)
                                    }
                                    completionHandler(WWValueResponse.init(value: responseArr, success: true))
                                }
                                else {
                                    completionHandler(WWValueResponse.init(success: false,message: "数据解析错误"))
                                }
                            }
                            else {
                                
                                completionHandler(WWValueResponse.init(success: false,message: "图片上传失败"))
                            }
                            return 
                        }
                    }
                    completionHandler(WWValueResponse.init(success: false,message: "图片上传失败"))
                })
            case .failure(let error):
               
                completionHandler(WWValueResponse.init(success: false,message: error.localizedDescription))
            }
        }
    }
    
    /// 提交头像
    class func commitAvatarData(_ urlPath: String,completionHandler:@escaping (WWResponse) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxCommon.UploadHeadPortrait"
        
        let params = ["Method":method, "url": urlPath, "AccountId": accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers:httpHeader ).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String {
                        if status == "OK" {
                            let result = dict["Result"] as? String
                            
                            if result != nil {
                                completionHandler(WWResponse.init(success: true))
                                return
                            }
                        }
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "数据有异常"))
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络错误"))
            }
        }
    }

}

class SuggestionModel {
    
    class func submitSuggestion(guid: String,username: String, phoneNumber: Int, orderNo: String,content: String,imageLists: [[String: String]], completionHandler:@escaping (WWResponse) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "KouFine.Handler.Core.AjaxOperate.SubmitProcess"
        let pageName = "MarTian.Edit.YiJianYuTouSu"
        let orderConfigId = "91C9F534-7C53-45A6-9F60-F16722EE9CF7"
        let approvalNote = "提交审批"
        let carbonList = ""
        
        var smartImageList = [[String: String]]()
        for item in imageLists {
            smartImageList.append(item)
        }
        let form = ["Name":username, "ContactInformation":"\(phoneNumber)", "Content":content, "OrderNo":orderNo, "SmartImageList":smartImageList, "ProductType":2] as [String : Any]
        let jsonData = ["ID":guid, "Form":form] as [String : Any]
        let jsonDataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let params = ["Method":method, "pageName": pageName, "orderConfigId":orderConfigId, "orderId":guid, "jsonData": jsonDataString, "approvalNote":approvalNote, "carbonList":carbonList, "AccountId":accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let value = response.result.value {
                    if value == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        completionHandler(WWResponse.init(success: false, message: value))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "数据错误"))
            }
            else  {
                
                completionHandler(WWResponse.init(success: false, message: "网络访问出错"))
            }
        }
    }
    

}

class AutoSignedInModel {
    class func updateAutoSignedInType(_ demandBaseMigrantWorkerID: String, autoSignedInType: AlertSignedInOption,completionHandler:@escaping (WWResponse) -> Void) {
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId,let userKey = model.userKey else {
            return
        }
        
        WWUser.sharedInstance.getToken(accountId, key: userKey) { (isSuccess) in
            if isSuccess {
                guard let httpHeader = mobile_cilent_headers() else {
                    return
                }
                let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWorker.SetAutoSignedInType"
                let params = ["Method": method, "DemandBaseMigrantWorkerID": demandBaseMigrantWorkerID, "AutoSignedInType": "\(autoSignedInType.rawValue)", "AccountId": accountId]
                Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON(completionHandler: { (response) in
                    if response.result.isSuccess {
                        if let dict = response.result.value as? [String: Any] {
                            
                            let status = dict["Status"] as? String
                            if status == "OK" {
                                completionHandler(WWResponse.init(success: true))
                            }
                            if status == "ERROR" {
                                let aResult = dict["Result"] as? String
                                completionHandler(WWResponse.init(success: false, message: aResult))
                            }
                            return
                        }
                        completionHandler(WWResponse.init(success: false, message: "数据有误"))
                    }
                    else {
                       completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
                    }
                })
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "获取token失败，请重新登录"))
            }
        }
    }
}


